import {EllipsisOutlined, PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {ProTable, TableDropdown} from '@ant-design/pro-components';
import {Button, Dropdown, Table, Space, Tag, Image} from 'antd';
import {useRef, useState} from 'react';
import request from 'umi-request';

import Edit from "./Edit";
import Detail from "./Detail";
import Bind from "./Bind";
import Settings from "./Settings";
import Add from "./Add";
import {
    ModalForm,
    ProForm,
    ProFormDateRangePicker,
    ProFormSelect,
    ProFormText,
} from '@ant-design/pro-components';
import {Form, message} from 'antd';
import {
    bindModels,
    bindModelsActions,
    chatterList,
    deleteModel,
    modelList,
    updateModelStatus
} from "@/services/chatter";
import {Popconfirm} from "antd/lib";
import {useRequest} from "@@/plugin-request/request";

export const waitTimePromise = async (time: number = 100) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
};

export const waitTime = async (time: number = 100) => {
    await waitTimePromise(time);
};

var actionRef = null;
type GithubIssueItem = {
    url: string;
    id: number;
    number: number;
    title: string;
    labels: {
        name: string;
        color: string;
    }[];
    state: string;
    comments: number;
    created_at: string;
    updated_at: string;
    closed_at?: string;
};


export type TableListItem = {
    modelCode: string;
    name: string;
    avatarUrl: number;
    gender: number;
    status: number;
    chatterName: string;
};


export default (props) => {
    const {run: addBind} = useRequest(bindModelsActions, {
        manual: true,
        onSuccess: (res) => {
            // onChange(1)
        }
    });

    const {chatterCode} = props;


    const {bindModelsCount} = props;
    actionRef = useRef<ActionType>();
    const [models, setModels] = useState([]);
    const [totalCnt,setTotalCnt] = useState(10);

    const columns: ProColumns<GithubIssueItem>[] = [
        {
            title: 'MID',
            dataIndex: 'modelCode',
            copyable: true,
            ellipsis: true,
        },
        {
            title: 'Nick Name',
            dataIndex: 'name',
            copyable: true,
            ellipsis: true,
            hideInSearch: true,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: 'Account Status',
            dataIndex: 'status',
            ellipsis: true,
            valueType: 'select',
            valueEnum: {
                99: {text: 'All'},
                1: {
                    text: 'Disabled',
                    status: 'warning',
                },
                2: {
                    text: 'Enabled',
                    status: 'Success',
                }
            },
        },
        {
            title: 'Avatar',
            dataIndex: 'avatarUrl',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => (
                <Image.PreviewGroup
                    items={[
                        record.avatarUrl,
                    ]}
                >
                    <Image
                        width={50}
                        src={record.avatarUrl}
                    />
                </Image.PreviewGroup>
            ),
        },
        {
            disable: true,
            title: 'Gender',
            dataIndex: 'gender',
            ellipsis: true,
            hideInSearch: true,
            valueType: 'select',
            valueEnum: {
                0: {text: 'unknow'},
                1: {
                    text: 'male',
                    status: 'Success',
                },
                2: {
                    text: 'female',
                    status: 'Error',
                }
            },
        },
        {
            title: 'PPV',
            dataIndex: 'hasPrivateType',
            ellipsis: true,
            valueType: 'select',
            hideInSearch: true,
            valueEnum: {
                99: {text: 'ALL'},
                0: {
                    text: 'NONE',
                    status: 'NONE',
                },
                1: {
                    text: 'PPV',
                    status: 'PPV'
                }
            }
        },
        // {
        //     title: 'Status',
        //     dataIndex: 'status',
        //     ellipsis: true,
        //     hideInSearch: true,
        //     hideInTable: true,
        //     valueType: 'select',
        //     valueEnum: {
        //         null: {text: 'all'},
        //         1: {
        //             text: 'waiting',
        //             status: 'warning',
        //         },
        //         2: {
        //             text: 'Pass',
        //             status: 'Success',
        //         },
        //         3: {
        //             text: 'Reject',
        //             status: 'Error',
        //         }
        //     },
        // },
        {
            title: 'Actions',
            valueType: 'option',
            key: 'option2',
            render: (text, record, _, action) => [
                // <a onClick={() => {
                //     let params = {chatterCode: chatterCode, modelsCode: [record.modelCode], action: 1}
                //     bindModelsActions(params).then(res => {
                //         message.success("Success");
                //         actionRef.current?.reload()
                //     })
                // }}
                // >
                //     Bind
                // </a>

                <Popconfirm
                    title="Bind Model"
                    description="Are you sure to Bind Model?"
                    onConfirm={(e) => {
                        let params = {chatterCode: chatterCode, modelsCode: [record.modelCode], action: 1}
                        bindModelsActions(params).then(res => {
                            message.success("Success");
                            actionRef.current?.reload()
                        })
                    }}
                    okText="Yes"
                    cancelText="No"
                >
                    <Button type={"primary"}>Bind</Button>
                </Popconfirm>
            ],
        },

    ];

    return (
        <div>

            <ProTable<TableListItem>
                rowSelection={{
                    // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                    // 注释该行则默认不显示下拉选项
                    selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                    defaultSelectedRowKeys: [],
                }}
                tableAlertRender={({
                                       selectedRowKeys,
                                       selectedRows,
                                       onCleanSelected,
                                   }) => {
                    setModels(selectedRowKeys)
                    return (
                        <Space size={24}>
                            <span>
                              已选 {selectedRowKeys.length} 项
                              <a style={{marginInlineStart: 8}} onClick={onCleanSelected}>
                                取消选择
                              </a>
                            </span>

                        </Space>
                    );
                }}
                tableAlertOptionRender={() => {
                    return (
                        <Space size={16}>
                            <Button type={"primary"} onClick={(e) => {
                                addBind({
                                    "chatterCode": chatterCode,
                                    "modelsCode": models,
                                    "action": 1
                                }).then(res=>{
                                    console.log(555,res)
                                    actionRef.current?.reload()
                                    message.success("bind success!!");
                                })
                            }}>Bind</Button>
                        </Space>
                    );
                }}
                columns={columns}
                actionRef={actionRef}
                cardBordered
                request={async (params) => {
                    params.assignedChatter = bindModelsCount > 0 ? 1 : 2;
                    // params.chatterCode = chatterCode;
                    params.userType = 3;
                    // params.status = 2;
                    let response = await modelList(params);
                    setTotalCnt(response.totalCnt);
                    return {data: response.list == null ? [] : response.list};
                }}

                columnsState={{
                    persistenceKey: 'pro-table-singe-demos',
                    persistenceType: 'localStorage',
                    onChange(value) {
                        // console.log('value: ', value);
                    },
                }}
                rowKey="modelCode"
                search={{
                    labelWidth: 'auto',
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                pagination={{
                    pageSize: 30,
                    total:totalCnt,
                    onChange: (page) => console.log(page),
                }}
                dateFormatter="string"
                headerTitle="models"
            />
        </div>
    );
};